package com.itheima.reggie.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.reggie.common.CustomException;
import com.itheima.reggie.dto.SetmealDto;
import com.itheima.reggie.mapper.SetmealMapper;
import com.itheima.reggie.pojo.Setmeal;
import com.itheima.reggie.pojo.SetmealDish;
import com.itheima.reggie.service.SetmealDishService;
import com.itheima.reggie.service.SetmealService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * @title: SetmealServiceImpl
 * @Author 椎名真白
 * @Date: 2022-04-28 14:56
 * @Version 1.0
 */

@Service
public class SetmealServiceImpl extends ServiceImpl<SetmealMapper, Setmeal> implements SetmealService {

    @Autowired
    private SetmealDishService setmealDishService;
    @Override
    @Transactional
    public void saveWithDish(SetmealDto setmealDto) {
        //保存套餐表数据
        this.save(setmealDto);
        //保存套餐菜品关系表数据 setmeal dish
        List<SetmealDish> setmealDishes = setmealDto.getSetmealDishes();
        //为每一个套餐菜品设置setmealID值
        setmealDishes.forEach(setmealDish -> setmealDish.setSetmealId(setmealDto.getId()));
        setmealDishService.saveBatch(setmealDishes);

    }

    @Override
    @Transactional
    public void removeWithDish(List<Long> ids) {
        //判断套餐是否可用删除
        //要删除的套餐的id在集合IDS中，其中状态为1，即售卖中的套餐不可以删除
        //构造分页选择器
        QueryWrapper<Setmeal> queryWrapper=new QueryWrapper<>();
        queryWrapper.in("id",ids);
        queryWrapper.eq("status",1);
        int count = this.count(queryWrapper);
        if(count>0){
            throw new CustomException("套餐售卖中，不可删除");
        }
        //没有一样的，可用进行删除
        this.removeByIds(ids);
        QueryWrapper<SetmealDish> queryWrapper1=new QueryWrapper<>();
        queryWrapper1.in("setmeal_id",ids);
        setmealDishService.remove(queryWrapper1);

    }

    @Override
    @Transactional
    public void upadteWithSetmealDish(SetmealDto setmealDto) {
        //更新套餐信息
        this.updateById(setmealDto);
        QueryWrapper<SetmealDish> queryWrapper=new QueryWrapper<>();
        //清空套餐中所有的菜品信息
        queryWrapper.eq("setmeal_id",setmealDto.getId());
        setmealDishService.remove(queryWrapper);
        //添加提交的口味信息
        List<SetmealDish> setmealDishes = setmealDto.getSetmealDishes();
        setmealDishes.forEach(setmealDish -> setmealDish.setSetmealId(setmealDto.getId()));
        setmealDishService.saveBatch(setmealDishes);
    }
}
